<script setup lang="ts">
import { addDrugList, queryImportHistory } from "@/api/machineClass";
import uploadFiles from "../uploadFiles/index.vue";
import { PxMessage, PxMessageBox } from "px-ui";
import { queryPabgeConfig } from "@/api/machineClass";
import { deleteReport, querySpecValues } from "@/api/machineApi";
import { reactive, ref, toRefs, nextTick, onMounted, getCurrentInstance } from "vue";
import barCharts from "@/views/machine/components/barChart/index.vue";

const { proxy }: any = getCurrentInstance();
const props = defineProps({
  activeName: {
    type: String,
    default: () => ""
  }
});

const tableLoading = ref(false);

const state = reactive<any>({
  classNameArr: [],
  queryParams: {
    subsystem: props.activeName,
    pageNum: 1,
    pageSize: 10
  },
  querySpcParams: {},
  total: 0,
  tableData: [],
  selectIds: []
});

const { selectIds, queryParams, classNameArr, total, tableData } = toRefs(state);
const dateRange = ref([]);

const pointsList = ref([
  "LL_3DT437P",
  "LL_3DT125P",
  "LL_CB70",
  "LL_Y_CH078",
  "LL_3DT199",
  "LL_N74824",
  "LL_boricacid",
  "LL_N3275",
  "LL_N2584",
  "LL_N77352P"
]);

const chartsKey = ref(Date.now());

const pageConfigData = ref<any>([]);

const barOptions = ref<any>({});

const getPageConfig = async () => {
  const data = await queryPabgeConfig();
  pageConfigData.value = data;
};

const getItemName = (code: string, system: string) => {
  const item = pageConfigData.value.find((item: any) => item.sysCode === system);
  return item.configList.find((item: any) => item.key === code).displayName;
};

// 表格多选框选中
const selectionChange = (val: any) => {
  selectIds.value = [];
  val.forEach((item: any) => {
    if (item.recordDate) {
      selectIds.value.push(item.recordDate);
    }
  });
};

// 删除
const handleDelete = () => {
  if (!selectIds.value.length) {
    PxMessage.warning("请至少选择一条数据");
    return;
  }
  PxMessageBox.confirm("是否确认删除【" + selectIds.value + "】记录？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    confirmButtonClass: "px-button--danger",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      const res: any = await deleteReport(selectIds.value);
      PxMessage({
        message: "删除成功",
        type: "success"
      });
      queryTable();
    })
    .catch(() => {});
};

const summaryTitle = ref(["加药日期", "MCHW", "LCHW", "HW", "HHW", "CW", "PCW"]);

const resolveArr = (arr: any) => {
  let data = arr.map((row: any, i) => {
    let list = [];
    for (let key in row) {
      list.push(row[key]);
    }
    return list;
  });
  return data;
};

const historyDialogVisible = ref(false);
const historyData = ref([]);

const handleImport = async () => {
  dialogVisible.value = true;
};

const historyPageNum = ref(1);
const historyPageSize = ref(10);
const historytotal = ref(0);

const getHistoryList = async () => {
  const data = await queryImportHistory({ pageNum: historyPageNum.value, pageSize: historyPageSize.value });
  historyData.value = data?.data;
  historytotal.value = data?.total;
};

const importHistory = () => {
  historyDialogVisible.value = true;
  nextTick(() => {
    getHistoryList();
  });
};

const dialogVisible = ref(false);
const submitHandler = async () => {
  const message = "上传成功";
  PxMessage.success(message);
  await queryTable();
};

// 是否展示N/A
const isShowNA = (val: any) => {
  return val && val.length > 0 && val.filter((item: any) => item.chemicalValue > 0).length > 0;
};

// 查询
const queryTable = async () => {
  tableLoading.value = true;
  const params = proxy.addDateRange(queryParams.value, dateRange.value, "recordDateStart", "recordDateEnd");
  const data: any = await addDrugList(params).catch(() => {
    tableLoading.value = false;
  });
  let resData = data.data ? data.data : [];
  // resData.forEach((item: any, index) => {
  //   item.summary.forEach((el: any, ind) => {
  //     el.index = summaryTitle.value.indexOf(el.systemName);
  //     item[el.systemName] = el.detectResultSummary === "1" ? true : false;
  //   });
  //   item.summary.sort((a, b) => a.index - b.index); // 按tabs顺序排列
  //   let arr = item.summary.map((el: any, ind) => {
  //     return {
  //       problemDesc: el.problemDesc,
  //       risk: el.risk,
  //       improvement: el.improvement,
  //       completionTime: el.completionTime,
  //       completionStatus: el.completionStatus
  //     };
  //   });
  //   let transData = resolveArr(arr);
  //   console.log(transData);
  //   item.summary = transData[0].map((col, i) => {
  //     return [
  //       originTitle.value[i],
  //       ...transData.map((row: any) => {
  //         return row[i];
  //       })
  //     ];
  //   });
  // });
  // console.log(resData);
  tableData.value = resData;
  total.value = data?.total;
  tableLoading.value = false;
  getbarCharts();
};

// 重置筛选条件
const resetTable = async () => {
  dateRange.value = [];
  queryParams.value = {
    subsystem: props.activeName,
    pageNum: 1,
    pageSize: 10
  };
  queryTable();
};

const handleDownload = (row: any) => {
  // 下载文件
  console.log(row.originalName);
  const url = row.fileUrl;
  const link = document.createElement("a");
  link.href = url;
  link.setAttribute("download", row.originalName);
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

const getbarCharts = async () => {
  const res: any = await querySpecValues(pointsList.value);
  const resData =
    res.rows && res.rows.length
      ? res
      : {
          innerServiceErrorMsg: null,
          total: 0,
          pageSize: 0,
          currentPageNum: 0,
          totalPage: 0,
          rows: [
            // {
            //   point: "PCW_PF",
            //   last_value: 22
            // },
            // {
            //   point: "PV_PF",
            //   last_value: 16
            // },
            // {
            //   point: "FAB-4F_T",
            //   last_value: 23
            // },
            // {
            //   point: "FAB-4F_T",
            //   last_value: 28
            // },
            // {
            //   point: "FAB-4F_T",
            //   last_value: 15
            // },
            // {
            //   point: "LCHW-CH-1_STATUS",
            //   last_value: 22
            // }
          ],
          jsonRows: null
        };
  const yAxis = [
    {
      type: "value"
    }
  ];
  const series = [
    {
      data: resData.rows.map(el => el.last_value),
      type: "bar",
      label: {
        show: true,
        position: "top",
        formatter: "{c}"
      },
      itemStyle: {
        color: "#4786FF"
      }
    }
  ];
  const option = {
    title: {
      text: "",
      textStyle: {
        fontSize: 16
      },
      subtext: "药品液位实时监视（L）",
      left: "left",
      top: "top",
      padding: [10, 0, 0, 20]
    },
    color: ["#4786FF"],
    grid: {
      left: "20px",
      top: "70px",
      right: "20px",
      bottom: "10px",
      containLabel: true
    },
    legend: {},
    tooltip: {
      trigger: "axis",
      confine: true,
      axisPointer: {
        type: "shadow"
      }
    },
    xAxis: {
      type: "category",
      boundarGap: false,
      data: resData.rows.map(el => el.point),
      axisTick: {
        alignWithLabel: true
      }
    },
    yAxis: yAxis,
    series: series
  };
  barOptions.value = option;
  chartsKey.value = Date.now();
};

onMounted(async () => {
  await getPageConfig();
  queryTable();
});
</script>

<template>
  <div class="tabsContent">
    <div class="tableCon">
      <px-form ref="formRef" class="custom-form-ui inspection-form" :model="queryParams" label-position="right" label-width="120px">
        <px-form-item label="加药日期" style="width: 430px">
          <px-date-picker
            v-model="dateRange"
            type="daterange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </px-form-item>
        <div class="query-btn-group">
          <px-button type="primary" @click="queryTable">查询</px-button>
          <px-button @click="resetTable">重置</px-button>
        </div>
      </px-form>
      <px-row :gutter="10" style="margin-bottom: 16px">
        <px-col :span="1.5">
          <px-button v-has="'MACHINE_ADD_DRUG_IMPORT_OVERVIEW'" type="primary" icon="" @click="handleImport">导入报告</px-button>
        </px-col>
        <px-col :span="1.5">
          <px-button v-has="'MACHINE_ADD_DRUG_IMPORT_HISTORY_OVERVIEW'" type="primary" plain icon="" @click="importHistory">导入历史</px-button>
        </px-col>
        <px-col :span="1.5">
          <px-button v-has="'MACHINE_ADD_DRUG_DELETE_OVERVIEW'" type="danger" plain icon="Delete" @click="handleDelete">删除</px-button>
        </px-col>
      </px-row>
      <px-scrollbar>
        <px-table
          v-loading="tableLoading"
          :data="tableData"
          class="inspection-table"
          height="calc(100vh -400px)"
          border
          @selection-change="selectionChange"
        >
          <px-table-column type="selection" width="55" />
          <px-table-column prop="recordDate" label="加药日期">
            <template #default="scope">
              <div>
                {{ scope.row.recordDate.split(" ")[0] }}
              </div>
            </template>
          </px-table-column>
          <px-table-column label="MCHW">
            <template #default="scope">
              <div>
                <div v-if="isShowNA(scope.row.detailMap.ZWLDS)">
                  <p v-for="item in scope.row.detailMap.ZWLDS.filter((item: any) => item.chemicalValue > 0)" :key="item.chemicalCode">
                    {{ getItemName(item.chemicalCode, "ZWLDS") }}: {{ item.chemicalValue + "L" }}
                  </p>
                </div>
                <px-icon v-else color="#10B981"><Picture /></px-icon>
              </div>
            </template>
          </px-table-column>
          <px-table-column label="LCHW">
            <template #default="scope">
              <div>
                <div v-if="isShowNA(scope.row.detailMap.DWLDS)">
                  <p v-for="item in scope.row.detailMap.DWLDS.filter((item: any) => item.chemicalValue > 0)" :key="item.chemicalCode">
                    {{ getItemName(item.chemicalCode, "DWLDS") }}: {{ item.chemicalValue + "L" }}
                  </p>
                </div>
                <px-icon v-else color="#10B981"><Picture /></px-icon>
              </div>
            </template>
          </px-table-column>
          <px-table-column label="HW">
            <template #default="scope">
              <div>
                <div v-if="isShowNA(scope.row.detailMap.DWLDS2)">
                  <p v-for="item in scope.row.detailMap.DWLDS2.filter((item: any) => item.chemicalValue > 0)" :key="item.chemicalCode">
                    {{ getItemName(item.chemicalCode, "DWLDS2") }}: {{ item.chemicalValue + "L" }}
                  </p>
                </div>
                <px-icon v-else color="#10B981"><Picture /></px-icon>
              </div>
            </template>
          </px-table-column>
          <px-table-column label="HHW">
            <template #default="scope">
              <div>
                <div v-if="isShowNA(scope.row.detailMap.GWRS)">
                  <p v-for="item in scope.row.detailMap.GWRS.filter((item: any) => item.chemicalValue > 0)" :key="item.chemicalCode">
                    {{ getItemName(item.chemicalCode, "GWRS") }}: {{ item.chemicalValue + "L" }}
                  </p>
                </div>
                <px-icon v-else color="#10B981"><Picture /></px-icon>
              </div>
            </template>
          </px-table-column>
          <px-table-column label="CW">
            <template #default="scope">
              <div>
                <div v-if="isShowNA(scope.row.detailMap.LQS)">
                  <p v-for="item in scope.row.detailMap.LQS.filter((item: any) => item.chemicalValue > 0)" :key="item.chemicalCode">
                    {{ getItemName(item.chemicalCode, "LQS") }}: {{ item.chemicalValue + "L" }}
                  </p>
                </div>
                <px-icon v-else color="#10B981"><Picture /></px-icon>
              </div>
            </template>
          </px-table-column>
          <px-table-column label="PCW">
            <template #default="scope">
              <div>
                <div v-if="isShowNA(scope.row.detailMap.PCW)">
                  <p v-for="item in scope.row.detailMap.PCW.filter((item: any) => item.chemicalValue > 0)" :key="item.chemicalCode">
                    {{ getItemName(item.chemicalCode, "PCW") }}: {{ item.chemicalValue + "L" }}
                  </p>
                </div>
                <px-icon v-else color="#10B981"><Picture /></px-icon>
              </div>
            </template>
          </px-table-column>
          <template #empty>
            <px-empty :image-size="150" />
          </template>
        </px-table>
      </px-scrollbar>
      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        class="inspection-pagination"
        :total="total"
        @pagination="queryTable"
      />
    </div>
    <!-- <div class="spcCon">
      <div class="spc_con">
        <div class="spc_item">
          <barCharts ref="barChartsDom" :key="chartsKey" :title="`药品液位实时监视`" :width="600" :options="barOptions" color="#4786FF" />
        </div>
      </div>
    </div> -->
    <uploadFiles v-if="dialogVisible" v-model="dialogVisible" @submit="submitHandler" />
    <px-dialog v-model="historyDialogVisible" width="60%" title="导入历史" align-center>
      <px-table :data="historyData" border class="inspection-table">
        <px-table-column label="序号" type="index" width="80" />
        <px-table-column prop="originalName" label="文件名称" show-overflow-tooltip />
        <px-table-column prop="createTime" label="Date" width="180" />
        <px-table-column label="操作" align="center" width="80">
          <template #default="scope">
            <px-tooltip content="下载" placement="top">
              <px-button link type="primary" icon="Download" @click="handleDownload(scope.row)" />
            </px-tooltip>
          </template>
        </px-table-column>
        <template #empty>
          <px-empty :image-size="150" />
        </template>
      </px-table>
      <pagination
        v-show="historytotal > 0"
        v-model:page="historyPageNum"
        v-model:limit="historyPageSize"
        style="margin-bottom: -10px"
        :total="historytotal"
        @pagination="getHistoryList"
      />
    </px-dialog>
  </div>
</template>

<style lang="scss" scoped>
.tabsContent {
  margin-top: 10px;

  .tableCon {
    padding: 0 24px 16px;

    .custom-form-ui {
      display: flex;

      .query-btn-group {
        display: flex;
        margin-bottom: 16px;
      }
    }
  }

  .spcCon {
    padding: 16px 20px 0;

    .spc_con {
      display: flex;
      flex-flow: row wrap;
      align-items: center;
      justify-content: space-between;
      min-width: 1300px;

      .spc_item {
        width: 100%;
        height: 468px;
        margin-bottom: 20px;
        border-radius: 4px;
      }
    }
  }
}
</style>
